﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using WinCustomsService.Model;

namespace WinCustomsService
{
    public class HttpClientHelper
    {
        public static string ApiUr = System.Configuration.ConfigurationManager.AppSettings["ApiUr"];

        public static void Test()
        {
            try
            {
                var client = new HttpClient();
                var response = client.GetStringAsync("https://newysc.himall.kuaidiantong.cn/admin/home/Getsetting").GetAwaiter().GetResult();
                LogHelper.WriteLog(JsonConvert.SerializeObject(response));
            }
            catch(Exception ex)
            {
                LogHelper.WriteLog(JsonConvert.SerializeObject(ex));
            }

        }

        /// <summary>
        /// 获取配置信息
        /// </summary>
        /// <returns></returns>
        public static CustomsPustSetting GetSetting()
        {
            CustomsPustSetting setting = new CustomsPustSetting();
            try
            {
                var client = new HttpClient();
                // LogHelper.WriteLog("获取配置信息url:" + ApiUr + "customsApi/setting");
                var response = client.GetStringAsync(ApiUr + "customsApi/setting").GetAwaiter().GetResult();
                // LogHelper.WriteLog("response:" + response);
                var message = JsonConvert.DeserializeObject<MessageModel<CustomsPustSetting>>(response);
                if(message.Success)
                    setting = message.Data;
            }
            catch(Exception ex)
            {
                LogHelper.WriteLog($"获取配置信息错误", ex);
            }
            return setting;
        }

        /// <summary>
        /// 需要请求的订单信息
        /// </summary>
        /// <returns></returns>
        public static CustomsPushPayInfo GetCustomsPush(out long id)
        {
            id = 0;
            CustomsPushPayInfo pushPayInfoModel = new CustomsPushPayInfo();
            try
            {
                var client = new HttpClient();
              //  LogHelper.WriteLog("url:"+ApiUr + "customsApi/details");
                var response = client.GetStringAsync(ApiUr + "customsApi/details").GetAwaiter().GetResult();
              //  LogHelper.WriteLog("message:" + response);
                var message = JsonConvert.DeserializeObject<MessageModel<CustomsPushPayInfo>>(response);
               
                if(message.Success)
                {
                    pushPayInfoModel = message.Data;
                    id = long.Parse(message.Msg);
                }

            }
            catch(Exception ex)
            {
                LogHelper.WriteLog("需求请求数据", ex);
            }

            return pushPayInfoModel;
        }


        /// <summary>
        /// 需要请求的订单信息
        /// </summary>
        /// <returns></returns>
        public static List<Push311Info> GetPush311Xml()
        {
            List<Push311Info> Push311InfoModel = new List<Push311Info>();
            try
            {
                var client = new HttpClient();
                var response = client.GetStringAsync(ApiUr + "customsApi/push311").GetAwaiter().GetResult();
                //LogHelper.WriteLog($"response:" + response);
                var message = JsonConvert.DeserializeObject<MessageModel<List<Push311Info>>>(response);
               // LogHelper.WriteLog("message:" + JsonConvert.SerializeObject(message));
                if(message.Success)
                    Push311InfoModel = message.Data;

            }
            catch(Exception ex)
            {
                LogHelper.WriteLog("需求请求数据", ex);
         
              
            }
            return Push311InfoModel;

        }


        /// <summary>
        /// 需要请求的订单信息
        /// </summary>
        /// <returns></returns>
        public static List<Push621Info> GetPush612Xml()
        {
            List<Push621Info> Push311InfoModel = new List<Push621Info>();
            try
            {
                var client = new HttpClient();
                var response = client.GetStringAsync(ApiUr + "customsApi/push621").GetAwaiter().GetResult();
               // LogHelper.WriteLog($"response:" + response);
                var message = JsonConvert.DeserializeObject<MessageModel<List<Push621Info>>>(response);
               // LogHelper.WriteLog("message:" + JsonConvert.SerializeObject(message));
                if(message.Success)
                    Push311InfoModel = message.Data;
            }
            catch(Exception ex)
            {
                LogHelper.WriteLog("需求请求数据", ex);
            }
            return Push311InfoModel;

        }


        /// <summary>
        /// 更新签名错误信息
        /// </summary>
        /// <param name="customsPush"></param>
        public static void UpdateSignError(CustomsPushInfo customsPush)
        {
            try
            {
                var dataJson = JsonConvert.SerializeObject(customsPush);
              
                var content = new StringContent(dataJson, Encoding.UTF8, "application/json");
                var client = new HttpClient();
                var response = client.PostAsync(ApiUr + "customsApi/signError", content).GetAwaiter().GetResult();
              
            }
            catch(Exception ex) {
                LogHelper.WriteLog($"更新签名错误信息",ex);
            }
           
        }


        /// <summary>
        /// 创建推送记录
        /// </summary>
        /// <param name="customsPush"></param>
        public static void CustomsCreate(CustomsClearanceEditor customs)
        {
            try
            {
                var dataJson = JsonConvert.SerializeObject(customs);
                var content = new StringContent(dataJson, Encoding.UTF8, "application/json");
                var client = new HttpClient();
                var response = client.PostAsync(ApiUr + "customsApi/customsCreate", content).GetAwaiter().GetResult();

            }
            catch(Exception ex)
            {
                LogHelper.WriteLog($"创建推送记录失败", ex);
            }

        }

        /// <summary>
        /// 更新上传海关结果返回
        /// </summary>
        /// <param name="customsPush"></param>
        public static void UpdateMessage(CustomsPushInfo customsPush)
        {
            try
            {
                var dataJson = JsonConvert.SerializeObject(customsPush);
                var content = new StringContent(dataJson, Encoding.UTF8, "application/json");
                var client = new HttpClient();
                var response = client.PostAsync(ApiUr + "customsApi/message", content).GetAwaiter().GetResult();
            }
            catch(Exception ex)
            {
                LogHelper.WriteLog($" 更新上传海关结果返回",ex);
            }
            
        }

        /// <summary>
        /// 上传数据到海关
        /// </summary>
        public static void UploadCustomsPushPay(CustomsPushPayInfo pushPayInfoModel)
        {
            try
            {
                CustomsPushInfo customsPush = new CustomsPushInfo();
                customsPush.SessionID = pushPayInfoModel.sessionID;

                var dataJson = JsonConvert.SerializeObject(pushPayInfoModel);
                var dataInfo = HttpUtility.UrlEncode(dataJson, Encoding.UTF8);
                // 需要使用payExInfoStr=UrlEncodeDate的键值组成报文内容
                var content = new StringContent("payExInfoStr=" + dataInfo, Encoding.UTF8, "application/x-www-form-urlencoded");

                var client = new HttpClient();
                var url = "https://customs.chinaport.gov.cn/ceb2grab/grab/realTimeDataUpload";
                LogHelper.WriteLog($"上传数据到海关" + dataInfo);
                var response = client.PostAsync(url, content).GetAwaiter().GetResult();

                var CustomsPushReturn = JsonConvert.DeserializeObject<CustomsPushReturnModel>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());

                if(CustomsPushReturn.code == "10000")
                    customsPush.Status = CustomsPushType.Complete;
                else
                {
                    if(CustomsPushReturn.Message.Contains("违反唯一约束条件"))
                        customsPush.Status = CustomsPushType.Complete;
                    else
                        customsPush.Status = CustomsPushType.fail;
                }

                customsPush.Data = dataJson;
                customsPush.Message = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                UpdateMessage(customsPush);
            }
            catch(Exception ex) {
                LogHelper.WriteLog($"上传数据到海关",ex);
            }
        }



        /// <summary>
        /// 上传数据到海关
        /// </summary>
        public static string  UploadCustoms311(Push311Submit submit)
        {
            try
            {
               
                var dataJson = JsonConvert.SerializeObject(submit);
                var content = new StringContent(dataJson, Encoding.UTF8, "application/json");
                var client = new HttpClient();
                LogHelper.WriteLog("订单dataJson：" + dataJson);
                var response = PostFormAsync("http://36.101.208.230:8090/cebcmsg", dataJson); //client.PostAsync("http://36.101.208.230:8090/cebcmsg", content).GetAwaiter().GetResult();
                LogHelper.WriteLog("订单response：" + response);
                return response;
            }
            catch(Exception ex)
            {
                
                LogHelper.WriteLog($"上传数据到海关", ex);
                return string.Empty;
            }
        }

        public static string UploadCustoms612(Push612Submit submit)
        {
            try
            {

                var dataJson = JsonConvert.SerializeObject(submit);
                var content = new StringContent(dataJson, Encoding.UTF8, "application/json");
                var client = new HttpClient();
                LogHelper.WriteLog("清单dataJson：" + dataJson);
                var response = PostFormAsync("http://36.101.208.230:8090/cebcmsg", dataJson); //client.PostAsync("http://36.101.208.230:8090/cebcmsg", content).GetAwaiter().GetResult();
                LogHelper.WriteLog("清单response：" + response);
                return response;
            }
            catch(Exception ex)
            {

                LogHelper.WriteLog($"上传数据到海关", ex);
                return string.Empty;
            }
        }

        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }
        public static string PostFormAsync(string url, string param)
        {
            string result = string.Empty;

            string strURL = url;
            try
            {
                System.Net.HttpWebRequest request;
                request = (HttpWebRequest)WebRequest.Create(strURL);
                request.Method = "POST";
                request.ContentType = "application/json;charset=UTF-8";
                string paraUrlCoded = param;

                byte[] payload;
                payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                request.ContentLength = payload.Length;
                Stream writer = request.GetRequestStream();
                writer.Write(payload, 0, payload.Length);
                writer.Close();
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using(Stream receiveStream = response.GetResponseStream())
                    {
                        using(StreamReader readerOfStream = new StreamReader(receiveStream, System.Text.Encoding.UTF8))
                        {
                            result = readerOfStream.ReadToEnd();
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                LogHelper.WriteLog("需求请求数据", ex);
               
            }
            return result;
        }

        /// <summary>
        /// 312查询
        /// </summary>
        /// <param name="qryid"></param>
        /// <param name="dxpid"></param>
        /// <returns></returns>
        public static string Ceb312msg(string qryid,string dxpid )
        {
            try
            {
                var client = new HttpClient();
                var response = client.GetStringAsync($"http://36.101.208.230:8090/ceb312msg?qryid={qryid}&dxpid={dxpid}").GetAwaiter().GetResult();
                return response;
            }
            catch(Exception ex)
            {
                LogHelper.WriteLog("需求请求数据", ex);


            }
            return string.Empty;

        }
    }
    
}
